package com.example.interview

import android.content.Intent
import android.graphics.Bitmap
import android.provider.MediaStore
import com.google.zxing.BinaryBitmap
import com.google.zxing.MultiFormatReader
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import android.app.Activity
import android.os.Bundle
import android.widget.Toast
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel


class MainActivity : FlutterActivity() {
    private val CHANNEL = "native_gallery_saver"
    private lateinit var gallerySaver: GallerySaver

    private val QR_SCANNER_CHANNEL = "qr_scanner_channel" // 新增的二维码扫描 Channel


    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)


        // 初始化 GallerySaver（保留你的原始逻辑）
        gallerySaver = GallerySaver(this)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
            .setMethodCallHandler { call, result ->
                when (call.method) {
                    "saveToGallery" -> {
                        val filePath: String? = call.argument("filePath")
                        if (filePath.isNullOrEmpty()) {
                            result.error("INVALID_ARGUMENT", "File path is null or empty", null)
                            return@setMethodCallHandler
                        }
                        if (gallerySaver.checkAndRequestPermissions(this)) {
                            val saveResult = gallerySaver.saveImageToGallery(filePath)
                            if (saveResult) {
                                result.success(true)
                            } else {
                                result.error("SAVE_FAILED", "Failed to save the image", null)
                            }
                        } else {
                            result.error("PERMISSION_DENIED", "Storage permissions are required", null)
                        }
                    }
                    else -> result.notImplemented()
                }
            }


        // 设置 qr_scanner_channel 的 MethodChannel（新增逻辑）
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, QR_SCANNER_CHANNEL)
            .setMethodCallHandler { call, result ->
                when (call.method) {
                     "startQrScan" -> {
                        val mode = call.argument<String>("mode")
                        if (mode == "camera") {
                            // 启动摄像头扫描
                            val intent = Intent(this, QrScanActivity::class.java)
                            startActivityForResult(intent, 1001)
                            pendingResult = result
                        } else if (mode == "gallery") {
                            // 从相册选择二维码
                            val galleryIntent = Intent(Intent.ACTION_PICK)
                            galleryIntent.type = "image/*"
                            startActivityForResult(galleryIntent, 1002)
                            pendingResult = result
                        } else {
                            result.error("INVALID_MODE", "Invalid scan mode: $mode", null)
                        }
                    }
                    else -> result.notImplemented()
                }
            }
        }



    // 用于暂存二维码扫描的结果对象
    private var pendingResult: MethodChannel.Result? = null

    // 处理 Activity 返回结果（二维码扫描结果）
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
         when (requestCode) {
            1001 -> { // 摄像头扫码结果
                if (resultCode == Activity.RESULT_OK) {
                    val scanResult = data?.getStringExtra("SCAN_RESULT")
                    pendingResult?.success(scanResult)
                } else {
                    pendingResult?.error("SCAN_FAILED", "QR Scan failed", null)
                }
            }
            1002 -> { // 从相册选择二维码
                if (resultCode == Activity.RESULT_OK && data != null) {
                    val imageUri = data.data
                    val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
                    val qrCodeResult = decodeQRCode(bitmap)
                    pendingResult?.success(qrCodeResult)
                } else {
                    pendingResult?.error("GALLERY_FAILED", "Failed to select an image", null)
                }
            }
        }
        pendingResult = null
    }


    // 解析二维码的函数
    private fun decodeQRCode(bitmap: Bitmap): String? {
        val reader = MultiFormatReader()
        val intArray = IntArray(bitmap.width * bitmap.height)
        bitmap.getPixels(intArray, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)

        val source = RGBLuminanceSource(bitmap.width, bitmap.height, intArray)
        val binaryBitmap = BinaryBitmap(HybridBinarizer(source))

        return try {
            val result = reader.decode(binaryBitmap)
            result.text
        } catch (e: Exception) {
            null
        }
    }


    // 处理权限结果
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == GallerySaver.PERMISSION_REQUEST_CODE) {
            if (grantResults.all { it == android.content.pm.PackageManager.PERMISSION_GRANTED }) {
                Toast.makeText(this, "Permissions granted", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "Permissions denied", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
